/*
错误捕获
*/
import * as types from './action-types'
import {delay,takeEvery,put,take,all} from 'redux-saga/effects'

function delay1(this: any,ms: number,ms2: number){
  return new Promise(function (resolve, reject) {
    setTimeout(() => {
      const number = Math.random();
      if (number > .5) {
        resolve(number);
      } else {
        reject('出错了');
      }
    }, ms + ms2);
  });
}

function delay2(this: any,ms: number,ms2: number){
  return new Promise(function (resolve, reject) {
    setTimeout(() => {
      const number = Math.random();
      if (number > .5) {
        //成功还是失败时通过状态码code来表示 code=0表示成功 code=1表示失败
        resolve({data: number, code: 0});
      } else {
        reject({data: '发生错误', code: 1});
      }
    }, ms + ms2);
  });
}

//第一种处理错误的风格
function* incrementAsync(): any{
  try{
    yield delay1(1000,100);
    yield put({type: types.INCREMENT})
  }catch (e) {
    console.log('e:',e);
    alert(e);
  }
}

//第二种处理错误的风格
function* incrementAsync2(): any{
  const result = yield delay2(1000,100);
  const {data, code} = result;
  if(code === 0){
    yield put({type:types.INCREMENT})
  }else{
    alert(data)
  }
  yield put({type: types.INCREMENT})
}

//saga就是一个generator函数
export function* watchAsyncIncrement(): any {
  yield takeEvery(types.ASYNC_INCREMENT, incrementAsync)
}

export default function* rootSaga(): any{
  yield all([watchAsyncIncrement(),incrementAsync2()])
}
